package com.yingdong.utils;

import static io.netty.handler.codec.http.HttpHeaderNames.CONNECTION;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_LENGTH;
import static io.netty.handler.codec.http.HttpHeaderNames.CONTENT_TYPE;
import static io.netty.handler.codec.http.HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN;
import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.QueryStringDecoder;

public class HttpUtils {
	public static FullHttpResponse getResponse(HttpRequest request, String value) throws UnsupportedEncodingException {
		FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(value.getBytes("UTF-8")));
		response.headers().set(CONTENT_TYPE, "text/plain");
		response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN,"*");
		response.headers().set(CONTENT_LENGTH, response.content().readableBytes());
		if (HttpUtil.isKeepAlive(request)) {
			response.headers().set(CONNECTION, HttpHeaderValues.KEEP_ALIVE);
		}
		return response;
	}

	public static String getParamerByNameFromGET(HttpRequest request, String name) {
		QueryStringDecoder decoderQuery = new QueryStringDecoder(request.uri());
		return getParameterByName(name, decoderQuery);
	}

	private static String getParameterByName(String name, QueryStringDecoder decoderQuery) {
		Map<String, List<String>> uriAttributes = decoderQuery.parameters();
		for (Entry<String, List<String>> attr : uriAttributes.entrySet()) {
			String key = attr.getKey();
			for (String attrVal : attr.getValue()) {
				if (key.equals(name)) {
					return attrVal;
				}
			}
		}
		return null;
	}
}
